package com.baizhi.cmfz.config;

import com.baizhi.cmfz.shiro.AuthencationReal;
import org.apache.shiro.mgt.DefaultSecurityManager;
import org.apache.shiro.mgt.SecurityManager;
import org.apache.shiro.spring.security.interceptor.AuthorizationAttributeSourceAdvisor;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.HashMap;
import java.util.Map;

@Configuration
public class ShiroConfig {

	/**
	 *
	 * @param securityManager 安全管理器
	 * @return 返回过滤器工厂
	 */
	@Bean

	public ShiroFilterFactoryBean getShiroFilterFactoryBean(SecurityManager securityManager){
//		创建ShiroFilterFactoryBean
		ShiroFilterFactoryBean shiroFilterFactoryBean = new ShiroFilterFactoryBean();
//		设置安全管理器规则
		//        配置拦截规则  哪些页面拦截 哪些不拦截  过滤器链
		Map map = new HashMap();
		/**
		 * anon 代表匿名可访问 就是不用登录就可以访问
		 *
		 * authc 代表登录后才能访问
		 *
		 * 支持通配符*
		 *
		 * 注意拦截规则 一个一个配置
		 */
		map.put("/login.jsp","anon");
		map.put("/admin/*","anon");
		map.put("/main.jsp", "authc");
		map.put("/articel/*","authc");
		map.put("/banner/*","authc");
		map.put("/log/*","authc");
		map.put("/user/*","authc");
		map.put("/guru/*", "authc");
		map.put("/menu/*", "authc");
		map.put("/jsp/*", "authc");

		shiroFilterFactoryBean.setFilterChainDefinitionMap(map);
//		设置一个安全管理器
		shiroFilterFactoryBean.setSecurityManager(securityManager);
		return shiroFilterFactoryBean;
	}

	/**
	 * 设置安全管理器
	 *
	 * @param authencationReal
	 * @return
	 */
	@Bean
	public SecurityManager getSecurityManager(AuthencationReal authencationReal){
		DefaultSecurityManager defaultSecurityManager = new DefaultWebSecurityManager();
//		设置realm
		defaultSecurityManager.setRealm(authencationReal);
		return defaultSecurityManager;
	}

	/**
	 *
	 * @return 返回自定义的数据领域
	 */
	@Bean
	public AuthencationReal getAuthenRealm(){
		return new AuthencationReal();
	}

	@Bean
	public AuthorizationAttributeSourceAdvisor authorizationAttributeSourceAdvisor(SecurityManager securityManager) {
		AuthorizationAttributeSourceAdvisor authorizationAttributeSourceAdvisor
			= new AuthorizationAttributeSourceAdvisor();
		authorizationAttributeSourceAdvisor.setSecurityManager(securityManager);
		return authorizationAttributeSourceAdvisor;
	}

}
